import React, { useEffect, useState } from 'react';
import { InboxOutlined } from '@ant-design/icons';
import type { UploadProps, ColumnsType } from 'antd';
import { message, Space, Table, Tag, Button } from 'antd';
import { Upload } from '../../util/serverLess';
import styled from 'styled-components';
import { connect } from 'dva';
import { history } from 'umi';

const Wrapper = styled.div`
  padding: 40px;
`;
const ImgContainer = styled.img`
  width: 80px;
  height: auto;
`;
const ButtonContainer = styled(Button)`
  margin-left: 10px;
`;
interface Props {
  userName: string;
  userId: string;
  [propsName: string]: any;
}

interface DataType {
  [propsName: string]: any;
}
const handelUrl = (url: string, type: string) => {
  if (type === 'open') {
    window.open(url);
  } else {
    navigator.clipboard.writeText(url);
    message.success('复制成功');
  }
};
const columns: ColumnsType<DataType> = [
  {
    title: '图片',
    dataIndex: 'url',
    key: 'url',
    render: (text: string) => <ImgContainer src={text} alt="" />,
  },
  {
    title: '名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '操作',
    dataIndex: 'url',
    key: () => {
      return new Date();
    },
    render: (text: any, record: any) => {
      console.log('操作', text, record);
      return (
        <div>
          <ButtonContainer
            type="primary"
            onClick={() => handelUrl(text, 'open')}
          >
            查看地址
          </ButtonContainer>
          <ButtonContainer
            type="primary"
            onClick={() => handelUrl(text, 'copy')}
          >
            复制地址
          </ButtonContainer>
        </div>
      );
    },
  },
];

const History: React.FC<Props> = (props) => {
  const [List, setList] = useState<Array<any>>([]);
  useEffect(() => {
    if (!props.userId) {
      history.replace('/home/login');
      return;
    }
    const data: any[] = [];
    Upload.find().then(
      (response: any) => {
        console.log('查找', response);
        response.forEach((item: any, index: number) => {
          data[index] = item.attributes.url.attributes;
        });
        setList(data);
      },
      (err) => {
        console.log('查找失败', err);
      },
    );
  }, []);
  return (
    <Wrapper>
      <Table columns={columns} dataSource={List} />
    </Wrapper>
  );
};
export default connect((state: any) => state.user)(History);
